import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/customer_info_model.dart';
import 'package:ls_work/viewmodel/service_execute/service_statistics_view_model.dart';

import '../../model/decode_qrcode_model.dart';
import '../../net/post_request.dart';
import '../../net/response/bed/bed_info_data.dart';
import '../../ui/service_execute/service_execute_home_page.dart';
import '../../util/utils.dart';

class ServiceExecuteHomeStatisticsViewModel extends BaseViewModel{
  ServiceExecuteHomeStatisticsViewModel(BuildContext context) : super(context);
  StatisticsData data = StatisticsData();

  var customerModel = CustomerInfoModel();

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.SERVICE_HOME_STATISTICS){
      data = event.obj;
      notifyListeners();
    }

    if(event.msgCode==MessageConfig.NFC_READ_IC_CARD){
      var cardNumber = event.obj as String;
      getCustomerInfo(cardNumber);
    }
  }

  Future<void> getCustomerInfo(String cardNumber) async {
    showLoadingDialog();
    try{
      var old = await customerModel.getCardAccount(physicalCardNo: cardNumber);
      hideDialog();
      Go().push(ServiceExecuteHomePage(customerId: old.data!.human!.id!.toString(),));
    }catch(e){
      showToast(e.toNetError());
      hideDialog();
    }
  }


  DecodeQrcodeModel model = new DecodeQrcodeModel();

  Future<void> _scanResult(String code) async {
    showLoadingDialog();
    try{
      var data = await model.decoed(code);
      hideDialog();
      switch(data.typeCode){
        case 1:
          // Go().push(ElderInfoPage(
          //   customerId: data.id.toInt(),
          // ));
          Go().push(ServiceExecuteHomePage(scanCode: code,customerId: data.id,));
          break;
        case 4:
          getCustomerByBed(data.id!);
          break;
      }
    }catch(e){
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }


  Future<void> getCustomerByBed(String bedId) async {
    showLoadingDialog();
    try{
      var data = await PostRequest.bedInfo(bedId);
      hideDialog();
      if ("0" == data['code'].toString()) {
        var bedInfo = BedInfoData.fromJson(data['data']);
        if(bedInfo.checkInElderInfoBean==null){
          showToast("该床位为空床");
        }else{
          var id = bedInfo.checkInElderInfoBean?.customerId.toString();
          Go().push(ServiceExecuteHomePage(customerId: id,));
        }

      }
    }catch(e){
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }



  ///扫码跳转
  Future<void> scanCode() async {
    var result = await Utils.scan();
    if (result != null) {
      _scanResult(result);
    }
  }




}